from django.shortcuts import render, HttpResponse

from rbac.models import UserInfo, Role, Permission, Menu


def distribute_permissions(request):
    """
    权限分配
    :param request:
    :return:
    """
    user_id = request.GET.get('uid')
    user_object = UserInfo.objects.filter(id=user_id).first()
    if not user_object:
        user_id = None

    role_id = request.GET.get('rid')
    role_object = Role.objects.filter(id=role_id).first()
    if not role_object:
        role_id = None

    # 保存角色
    if request.method == "POST" and request.POST.get('type') == 'role':
        if not user_object:
            return HttpResponse('用户不存在，请重新选择')
        role_id_list = request.POST.getlist('roles')
        user_object.roles.set(role_id_list)
    if request.method == "POST" and request.POST.get('type') == 'permission':
        if not role_object:
            return HttpResponse("角色不存在，请重新选择")
        perrmission_id_list = request.POST.getlist('permissions')
        role_object.permissions.set(perrmission_id_list)

    # 获取当前用户的所有角色
    if user_id:
        user_has_roles = user_object.roles.all()
    else:
        user_has_roles = []
    user_has_roles_dict = {item.id: None for item in user_has_roles}

    # 获取当前用户的所有权限
    # 如果选中了角色，优选选中角色拥有的权限
    if role_object:
        user_has_permissions = role_object.permissions.all()
        user_has_permissions_dict = {item.id: None for item in user_has_permissions}
    elif user_object:
        user_has_permissions = user_object.roles.filter(permissions__isnull=False).values('permissions__id').distinct()
        user_has_permissions_dict = {item['permissions__id']: None for item in user_has_permissions}
    else:
        user_has_permissions_dict = {}

    # 获取所有用户
    all_user_list = UserInfo.objects.all()
    # 获取所有角色
    all_role_list = Role.objects.all()

    all_menu_dict = {}
    # 获取所有菜单
    all_menu_list = Menu.objects.values('id', 'title')
    for item in all_menu_list:
        item['children'] = []
        all_menu_dict[item['id']] = item
    # 所有二级菜单
    all_second_menu_list = Permission.objects.filter(menu_id__isnull=False).values('id', 'title', 'menu_id')
    all_second_menu_dict = {}
    for row in all_second_menu_list:
        row['children'] = []
        all_second_menu_dict[row['id']] = row
        menu_id = row['menu_id']
        all_menu_dict[menu_id]['children'].append(row)

    # 所有三级菜单(不能做菜单的权限）

    all_permission_list = Permission.objects.filter(pid_id__isnull=False).values('id', 'title', 'pid')

    for row in all_permission_list:
        pid = row['pid']
        if not pid:
            continue
        all_second_menu_dict[pid]['children'].append(row)
    return render(
        request,
        'rbac/distribute_permissions.html',
        {'user_list': all_user_list,
         'role_list': all_role_list,
         'all_menu_list': all_menu_list,
         'uid': user_id,
         'user_has_roles_dict': user_has_roles_dict,
         'user_has_permissions_dict': user_has_permissions_dict,
         'role_id': role_id
         }
    )
